import { Upload, Button,message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React from 'react'


 const  getFileMimeType= (file)=> {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    return new Promise((resolve, reject) => {
        reader.onload = (event) => {
            try {
                let buffer = [...Buffer.from(event.target.result)];
                // 仅要文件的前四位就够了
                buffer = buffer.splice(0, 4);
                buffer.forEach((num, i, arr) => {
                    arr[i] = num.toString(16).padStart(2, '0');
                });
                // 74657374 是 csv 的文件头
                resolve(buffer.join('') === '74657374');
            } catch (e) {
                // 读取文件头出错 默认不是合法文件类型
                reject();
            }
        }
    })
}
 const beforeUpload = (file) => {
    return new Promise(async (resolve, reject) => {
        const isExcel = await getFileMimeType(file); // 调用上面代码
        if (!isExcel) {
            message.error('上传失败！仅支持文件类型为csv的文件');
            reject();
        }
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
            message.error('上传文件不能超过 10MB!');
            reject();
        }
        resolve();
    });
}


// function beforeUpload(file) {
//     const isJpgOrPng = file.type === '*.csv' 
//     if (!isJpgOrPng) {
//       message.error('You can only upload *.csv file!');
//     }
//     const isLt2M = file.size / 1024 / 1024 < 2;
//     if (!isLt2M) {
//       message.error('Image must smaller than 2MB!');
//     }
//     return isJpgOrPng && isLt2M;
//   }
  


export default class MyUpload extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            fileList: [
    
            ],
        };
    }


    handleChange = info => {

        let fileList = [...info.fileList];
        console.log(info.fileList[0].name)
        fileList = fileList.slice(-1);
        // info.fileList = info.fileList.slice(-1);
        fileList = fileList.map(file => {
            if (file.response) {
                file.url = file.response.url;
            }
            return file;
        });

        this.setState({ fileList });
    };




    render() {
        const props = {
            action: '/api/uplode',
            onChange: this.handleChange,
            multiple: true,
            accept: '.csv',
            beforeUpload: beforeUpload
        };
        return (
            <Upload {...props} fileList={this.state.fileList}>
                <Button icon={<UploadOutlined />}>导入</Button>
            </Upload>
        );
    }
}


